# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://api.9127pay.com/api/create.jsp?time={}&sign={}'
_QUERY_GATEWAY = 'https://api.9127pay.com/api/queryorder.php?time={}&sign={}'
_QUERY_PAYTYPE = 'https://api.9127pay.com/api/querysupportedmethod?merchant_id={}time={}&sign={}'

APP_CONF = {
    'KS': {
        'API_KEY': '93419585-e497-4a9c-b73f-f3fde8c7bb32'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, ts, key):
    '''  生成下单签名 '''
    s = '{}{}{}'.format(p_data, ts, key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().upper()
    _LOGGER.info(u'kspay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(params['json'], params['time'], key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest().upper()
    if sign != calculated_sign:
        _LOGGER.info("kspay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def query_available_pays(app_id):
    ts = tz.now_ts()
    api_key = _get_api_key(app_id)
    s = '{}{}{}'.format(app_id, ts, api_key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().upper()
    gate_url = _QUERY_PAYTYPE.format(app_id, ts, sign)
    response = requests.post(gate_url, timeout=3)
    print response.text


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']  # wechat or alipay
    if service == 'unionpay':
        payment = 'unionpay'
    elif service == 'alipay':
        payment = 'alipay'
    elif service == 'wechat':
        payment = 'wxpay'
    elif service == 'qq':
        payment = 'qqpay'
    elif service == 'jd':
        payment = 'jdpay'
    else:
        payment = 'unionpay'
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    pay_amount = _fix_pay_amount(pay, pay_amount)
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/kspay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("payment", payment),
        ("bill_price", '%.2f' % pay_amount),
        ("info", {
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "device_type": user_info.get('device_type') or 'android',
            "tel": user_info.get('tel') or ''
        })
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _GATEWAY.format(ts, sign)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('kspay brefore data: %s\n%s', gate_url, response.text)
    if response.status_code == 200:
        # response text is a pure html text
        res_obj = json.loads(response.text)
        pay_url = res_obj['data']['qrcode']
        charge_resp.update({
            'charge_info': pay_url,
        })
        _LOGGER.info("kspay data after charge: %s", pay_url)
    else:
        _LOGGER.warn('kspay data error, status_code: %s', response.status_code)
    return charge_resp


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("kspay notify data: %s", data)
    verify_notify_sign(data, api_key)
    data = json.loads(data['json'])
    pay_id = data['business_order']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('kspay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['pay_status'])
    trade_no = data.get('business_order')
    total_fee = float(data['payed_money'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 10000:
        _LOGGER.info('kspay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    charge_resp = {}
    api_key = _get_api_key(app_id)
    p_dict = {
        'merchant_id': app_id,
        'order_id': str(pay_id)
    }
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _QUERY_GATEWAY.format(ts, sign)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    if response.status_code == 200:
        data = json.loads(response.text)
        print data
        trade_no = pay_id
        trade_status = int(data['status'])
        total_fee = float(data['payed_money'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 10000:
            _LOGGER.info('kspay query order success, mch_id:%s pay_id:%s' % (
                pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('kspay data error, status_code: %s', response.status_code)
